package com.gongfutrip.trans.client;

import com.gongfutrip.trans.Consumer;
import com.gongfutrip.trans.client.common.ConsumerConfig;
import com.gongfutrip.trans.client.exception.ClientException;
import com.gongfutrip.trans.client.processor.ShoppingProcessor;
import com.gongfutrip.trans.remoting.ChannelEventListener;
import com.gongfutrip.trans.remoting.NettyRemotingServer;
import com.gongfutrip.trans.remoting.RemotingServer;
import java.io.UnsupportedEncodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConsumerImpl implements Consumer {

    private static final Logger logger = LoggerFactory.getLogger(ConsumerImpl.class);

    private final RemotingServer remotingServer;
    private final ConsumerConfig consumerConfig;

    public ConsumerImpl(final ConsumerConfig consumerConfig) {
        this(consumerConfig, null);
    }


    public ConsumerImpl(final ConsumerConfig consumerConfig,
        final ChannelEventListener channelEventListener) {
        this.remotingServer = new NettyRemotingServer(consumerConfig, channelEventListener);
        this.consumerConfig = new ConsumerConfig();
        try {
            this.initialize();
            this.start();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }


    public void initialize() {
        remotingServer
            .registerProcessor(BusinesssRequestCode.SHOPPINBG, new ShoppingProcessor(), null);
    }

    @Override
    public void start() throws ClientException {
        logger.info("#################### begin start consumer ####################");
        this.remotingServer.start();
        logger.info("#################### start consumer success ####################");

    }

    @Override
    public void shutdown() {
        this.remotingServer.start();
    }

    public static void main(String[] args)
        throws UnsupportedEncodingException, ClientException, InterruptedException {
        new ConsumerImpl(new ConsumerConfig());
    }
}
